package com.project.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.EmployeeBean;
import com.project.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("em")
public class EmController {
    @Autowired
    private IEmployeeService service;

    @RequestMapping("findAll")
    public List<EmployeeBean> findAll(){
        return service.findAll();
    }

    @RequestMapping("dismission")
    public String dismission(Integer id){
        service.dimission(id);
        return "ok";
    }

    //@Valid 表示需将提交数据进行校验，BindingResult用于存放校验失败信息
    @RequestMapping("add")
    public String add(@Valid EmployeeBean em, BindingResult br) throws Exception{
        if(br.hasErrors()){//判断是否有验证失败信息
            //得到校验失败集合
            List<FieldError> errorList = br.getFieldErrors();
            //将校验失败集合转化为json字符串发送给客户端
            ObjectMapper om = new ObjectMapper();
            String errorInfo = om.writeValueAsString(errorList);
            return  errorInfo;
        }

        service.add(em);
        return "ok";
    }

    @RequestMapping("findById")
    public EmployeeBean findById(Integer id){
        return service.findById(id);
    }

    @RequestMapping("update")
    public String update(Integer id,Integer money){
        service.update(id,money);
        return "ok";
    }
}
